<?php
namespace app\home\controller;

use app\admin\model\Config;
use app\admin\model\TaskCategory;
use app\admin\model\Uploads;
use app\home\model\Area;
use app\home\model\CreditRecord;
use app\home\model\Member;
use think\Db;
use think\Log;
use app\home\model\Follow;
class Task extends Base{

    public $kc_money = 0;
    
    public function _initialize()
    {
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['kc_money'])){
                $this->kc_money = round(floatval($setting['kc_money']/100),2);
            }
        }
    }

    public function see(){
        //任务列表
        $params = request()->request();
        if(check_array($params)){
            array_trim($params);
        }
      $param['is_complete']=0;
      $param['out_stock_flag'] = 0;
      $param['is_display'] = 1;
      $param['is_stop'] = 0;

        //分页
    $size=params('size')?:7;
    $page=params('page')?:1;

    $start=$size*($page-1);

	$param['is_over']=0;
	$param['is_back']=0;

    $tasks = Db::name('task')->alias('a')->where($param)->order("number desc,create_time desc")->limit($start,$size)->join('seepackage b','a.id = b.task_id','LEFT')->group('id')->select();

    //var_dump(Db::name('task')->getLastSql());exit;
    
        if(!empty($this->member['uid'])){
            $uid = $this->member['uid'];
        }else{
          $uid = '';
        }    
    
    	$seepackage_model=db('seepackage');
    	$seepackage_record_model=db('seepackage_record');

        foreach($tasks as $key=>$val){
            if($uid){
	            $tasks[$key]['is_get']=$seepackage_record_model->where(['uid'=>$uid,'task_id'=>$val['task_id']])->find()?1:0;
            }else{
	            $tasks[$key]['is_get']=0;
            }
            $total=$seepackage_model->where(['task_id'=>$val['task_id']])->sum('number');
            $done=$seepackage_record_model->where(['task_id'=>$val['task_id']])->count();
            $tasks[$key]['left']=$total-$done;
       }

            if(request()->isAjax()){
              return  $this->fetch('_see',['tasks'=>$tasks]);
            }
        /*if(request()->isAjax()){
            if(empty($tasks)){
                return json($tasks);
                message('没有更多任务','','error');
            }
            return json($tasks);
            message($tasks,'','success');
        }*/
        //return json($tasks);
        


         $top_list=Db::name('task')->where(['top_end_time'=>['gt',TIMESTAMP]])->order('top_time desc')->select();

        return $this->fetch(__FUNCTION__,[
       
            'tasks' => $tasks,
      
            'uid'   =>$uid
           
 
        ]);
    }


    public function category(){
        $background = array('background-image: linear-gradient(to top, #c471f5 0%, #fa71cd 100%);',
        'background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);',
        'background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);',
        'background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%);',
        'background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);',
        'background-image: linear-gradient(to right, #b8cbb8 0%, #b8cbb8 0%, #b465da 0%, #cf6cc9 33%, #ee609c 66%, #ee609c 100%);',
        'background-image: linear-gradient(180deg, #2af598 0%, #009efd 100%);',
        'background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);',
        'background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);',
        'background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);',
        'background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);',
        );
        $list=Db::name('task_category')->where(['is_display'=>1])->order('order_by desc')->select();
        return $this->fetch(__FUNCTION__,[
            'category' => $list,'background'=>$background
        ]);
    }

    public function index(){
       // $category_id = floor(trim(params('category_id')))?floor(trim(params('category_id'))):0;
      //  $paixu = trim(params('paixu'))?trim(params('paixu')):1;


      $category_id=params('category_id');
      $paixu=params('paixu');

        //任务列表
        $params = request()->request();
        if(check_array($params)){
            array_trim($params);
        }
      $param['is_complete']=0;
      $param['out_stock_flag'] = 0;
      $param['is_display'] = 1;
      $param['is_stop'] = 0;

          $type=params('type');
       if($type == 'simple'){
          $param['category_id']=['in','2,3,7,8,11'];
        }
         if($type == 'high'){
          $param['category_id']=['in','4,6,7,9,10'];
        }


        $id =  params('id');
        if(!empty($id)){
             $param['category_id'] = $id;
        }
        
       $category_ids=params('category_ids');
    //   if($category_ids){
    //     $param['category_id']=['in',$category_ids];
    //   }
    
        
        $keyword = trim(params('keyword'));
        if($keyword != ''){
        //   if(is_numeric($keyword)){
        //     $param['id']=$keyword;
        //   }else{
            $param['title']=['LIKE','%'.$keyword.'%'];
            
        //   }

        }
			//db('task')->where('id',3301)->setField('top_time',time());
			
			
            $order_str='';

            if($paixu == 2){
              $order_str='create_time desc';
            } elseif($paixu == 3){
              $order_str='unit_price desc,create_time desc';
            }elseif($paixu == 4){
              //完成任务量
              $order_str='join_num desc';
            }else{
              $order_str='top_time desc,update_time desc';

            }

        if($category_id){
            //$param['category_id'] = $category_id;

            $catename = Db::name('task_category')->where(['id'=>$category_id])->find();
        }else{
            $catename['title'] = '全部';

        }


//http://color.oulu.me/
        $background = array('background-image: linear-gradient(to top, #c471f5 0%, #fa71cd 100%);',
        'background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);',
        'background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);',
        'background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%);',
        'background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);',
        'background-image: linear-gradient(to right, #b8cbb8 0%, #b8cbb8 0%, #b465da 0%, #cf6cc9 33%, #ee609c 66%, #ee609c 100%);',
        'background-image: linear-gradient(180deg, #2af598 0%, #009efd 100%);',
        'background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);',
        'background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);',
        'background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);',
        'background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);',
        );

        //分页
    $size=params('size')?:15;
    $page=params('page')?:1;

    $start=$size*($page-1);

    //    $data=$model->field('content,message_id,type,send_time,title')->order('message_id desc')->limit($start,$size)->select();

        // return json_encode($param);
          $tasks = Db::name('task')->where($param)
          //->whereOr('appName','like',$keyword)
          ->order($order_str)
          ->limit($start,$size)
          ->select();

    //var_dump(Db::name('task')->getLastSql());exit;
        $taskcate = Db::name('task_category')->where(['is_display'=>1])->order("order_by desc")->select();
        $redpackage_model=db('redpackage');
        $seepackage_model=db('seepackage');
        foreach($tasks as $key=>$val){
            $member_rs = Db::name("member")->where("uid = {$val['uid']}")->field("avatar,level_time")->find();
            $tasks[$key]=$val;
            $tasks[$key]["avatar"]=!empty($member_rs["avatar"])?$member_rs["avatar"]:"/static/home/mobile/picture/user.png";
            //新修改 2019-05-08
            $catagoryname=Db::name("task_category")->where("id = {$val['category_id']}")->field("title")->find();
            $tasks[$key]['cataname']=$catagoryname['title'];
            $tasks[$key]['redpackage']=$redpackage_model->where(['task_id'=>$val['id'],'is_over'=>0])->find()?1:0;
            $tasks[$key]['seepackage']=$seepackage_model->where(['task_id'=>$val['id'],'is_over'=>0,'is_back'=>0])->find()?1:0;
       		$tasks[$key]['is_vip']=$member_rs['level_time']>time()?1:0;
       		$tasks[$key]['is_top']=$val['top_end_time']>time()?1:0;
       		$tasks[$key]['unit_price'] = $val['unit_price'] - $val['unit_price']*$this->kc_money;
        }

            if(request()->isAjax()){
              return  $this->fetch('_index',['tasks'=>$tasks]);
            }
        /*if(request()->isAjax()){
            if(empty($tasks)){
                return json($tasks);
                message('没有更多任务','','error');
            }
            return json($tasks);
            message($tasks,'','success');
        }*/
        //return json($tasks);
        if(!empty($this->member['uid'])){
            $uid = $this->member['uid'];
        }else{
          $uid = '';
        }

         $top_list=Db::name('task')->where(['top_end_time'=>['gt',TIMESTAMP]])->order('top_time desc')->select();

        return $this->fetch(__FUNCTION__,[
            'top_list'=>$top_list,
            'tasks' => $tasks,
            'taskcate' => $taskcate,
            'category_id' =>$category_id,
            'catename' =>$catename['title'],
            'paixu'=>$paixu,
            'keyword'=>$keyword,
            'id'=>$id,
            'touteng' =>1,
            'background' => $background,
            'uid'   =>$uid,
            'type'=>$type,
            'category_ids'=>$category_ids,
            'category_ids_arr'=>explode(',',$category_ids),
        ]);
    }

        public function userprotocol(){
        	if(request()->isAjax()){
        		
		        echo $this->fetch(__FUNCTION__);
        	}else{
        		
		        return $this->fetch(__FUNCTION__);
        	}
    }
    
    
    
    public function myindex(){
        $category_id = floor(trim(params('category_id')))?floor(trim(params('category_id'))):0;
        $paixu = trim(params('paixu'))?trim(params('paixu')):1;
        //任务列表
        $params = request()->request();
        if(check_array($params)){
            array_trim($params);
        }
        $param['is_complete']=0;
      $param['out_stock_flag'] = 0;
      $param['is_display'] = 1;
      $param['is_stop'] = 0;  
      	$keyword = trim(params('keyword'));
      	if($keyword != ''){
         $param['title']=['LIKE','%'.$keyword.'%']; 
        }
        if($category_id){
            $param['category_id'] = $category_id;

            $catename = Db::name('task_category')->where(['id'=>$category_id])->find();
            if($paixu == 2){
                $tasks =Db::name('task')->where($param)->order('update_time desc,top_time desc')->select();
            } elseif($paixu == 3){
                $tasks =Db::name('task')->where($param)->order('unit_price desc,top_time desc')->select();
            }else{
                $tasks = Db::name('task')->where($param)->order('top_time desc')->select();
            }

        }else{ 
            if($paixu == 2){
                $tasks =Db::name('task')->where($param)->order('update_time desc,top_time desc')->select();
            } elseif($paixu == 3){
                $tasks =Db::name('task')->where($param)->order('unit_price desc,top_time desc')->select();
            }else{
              	if($keyword != ''){
                	$tasks = Db::name('task')->where($param)->order('top_time desc')->select();
                }else{
                $tasks = Db::name('task')->where($param)->order('top_time desc')->select();}
            }
            $catename['title'] = '全部';
        }
		//var_dump(Db::name('task')->getLastSql());exit;
        $taskcate = Db::name('task_category')->where(['is_display'=>1])->order("order_by desc")->select();
        foreach($tasks as $key=>$val){
            $member_rs = Db::name("member")->where("uid = {$val['uid']}")->field("avatar")->find();
            $tasks[$key]=$val;
            $tasks[$key]["avatar"]=!empty($member_rs["avatar"])?to_media($member_rs["avatar"]):"/static/home/mobile/picture/user.png";
            //新修改 2019-05-08
            $catagoryname=Db::name("task_category")->where("id = {$val['category_id']}")->field("title")->find();
            $tasks[$key]['cataname']=$catagoryname['title'];
        }
  
        var_dump($tasks);
    }

      
    
  //上传图片
  public function upimg(){

  	 $file = request()->file('file');

      //七牛
      $qninfo = $this->qiniuupload($file);
      if(!$qninfo){
             message('图片错误','','error');
      }
    $data['img'] = $qninfo;
    echo json_encode($data);
  }
  



    public function detail(){
    
        $is_can_op = 0;
        $id = floor(trim(params('id')));
        if(!check_id($id)){
            message('任务ID错误','','error');
        }
        
        $item = \app\home\model\Task::getInfoById($id);
    
        if(empty($item)){
            message('任务不存在','','error');
        }
        if(!empty($this->member['uid']) && $item['uid'] == $this->member['uid']){
            $is_can_op = 1;
        }
        $member_uid = '';
        if(!empty($this->member['uid'])){
        	$member_uid = $this->member['uid'];
        }

        $item['audit_num'] = \app\home\model\TaskJoin::getAuditNumById($id);

        $operate_steps = \app\home\model\Task::getOperateStepsById($id);
      	$has_tu =0;
      	$has_wz = 0;
      	$has_rw = 0;
   		foreach($operate_steps as $v){
        	if($v['type']==2||$v['type']==4){
              $has_tu++;
            }
          if($v['type']==1){
              $has_wz++;
            }
          if($v['type']==3){
              $has_rw++;
            }
        }
        $member_task_join_info = NULL;
        if (isset($this->member['uid']) && $this->member['uid'] > 0) {
            $member_task_join_info = \app\home\model\TaskJoin::getInfoByTaskIdAndUid($id, $this->member['uid']);
        }

        $allow_accept = true;
        if ($item['start_time'] > TIMESTAMP || $item['origin_end_time'] < TIMESTAMP) {
            $allow_accept = false;
        }
      	if(mb_strlen($item['appName']))
        {
          $item['appName']=mb_substr($item['appName'],0,6,"UTF8");
        }
       $whereparam=array();
      $whereparam['task_id']=$item['id'];
      $whereparam['status']=3;
      	$successNum= Db::name('task_join')->where($whereparam)->count();
      $item['sucess']=$successNum;
        $gory = Db::name("task_category")->where("id = {$item['category_id']}")->find();
        $item['category_name']=$gory['title'];
        if($gory['only_level'] == '1'||$gory['only_level']<1){
            $msgtt = "普通会员及以上可接";
        }elseif ($gory['only_level'] == '2') {
             $msgtt = "VIP会员及以上可接";
        }elseif ($gory['only_level'] == '3') {
             $msgtt = "高级VIP会员及以上可接";
        }else{
             $msgtt = "特级VIP会员及以上可接";
        }
		
      //2019-08-05 修改是否关以及VIP判断，老铁有报错，注意判断$member
        if(!empty($this->member['uid']))
        {
          $levels = Db::name("member")->where("uid = {$this->member['uid']}")->find();
          $msg_level = Db::name("member_level")->where("level = {$levels['level']}")->find();
          $isFollow = Follow::getIsFollow($this->member['uid'], $item['uid']);
          $msg_levels=$msg_level['title'];
           //判断VIP的积分数
          if($msg_level['title']=="VIP会员")
          {
            $maobi=(int)$item['give_credit1'];
              $maobi=$maobi*2;
          }
          else
          {
            $maobi=(int)$item['give_credit1'];
           }
        }
        else
        {
          $maobi=(int)$item['give_credit1'];
          $isFollow="";
          $msg_levels="";
        }
        $task_joins = db('task_join')->where('task_id',$id)->field('uid,status,check_text_content,check_text_content2,thumbs,delflag,reason,create_time,audit_time')->select();
        foreach ($task_joins as $k=>$v){
        	$task_joins[$k]['nickname'] = db('member')->where('uid',$v['uid'])->value('nickname');
        
        	$task_joins[$k]['thumbs'] = unserialize($v['thumbs']);
        }
        $seepackage=0;
        if($member_uid){
        	$is_send=db('seepackage')->where(['task_id'=>$id,'is_over'=>0,'is_back'=>0])->find();
       
        	if($is_send){
		        $seepackage=\db('seepackage_record')->where(['task_id'=>$id,'uid'=>$member_uid])->find()?0:1;
        	}
        	if($is_send['uid'] == $member_uid){
        		$is_send=0;
        	}
        }else{
        	$seepackage=0;
        }
        
        if($member_task_join_info && $member_task_join_info['status'] == 2){
        	$seepackage=0;
        }
       //增加浏览次数
       $item['unit_price'] = $item['unit_price'] - $item['unit_price'] * $this->kc_money;
		db('task')->where('id',$id)->setInc('click',1);
        return $this->fetch(__FUNCTION__,[
            'item' => $item,
            'is_can_op' => $is_can_op,
            'operate_steps' => $operate_steps,
            'member_task_join_info' => $member_task_join_info,
            'allow_accept' => $allow_accept,
            'msgtt' => $msgtt,
			'isFollow'=>$isFollow,
            'maobi'=>$maobi,
            'msg_levels'=>$msg_levels,
            'check_text_content' => !empty($item['check_text_content'])?$item['check_text_content']:'',
            'check_text_content_js' => !empty($item['check_text_content'])?str_replace(array("\r", "\n"), array("", "\\n"), $item['check_text_content']):'',
            'check_text_flag' => !empty($item['check_text_content'])?'1':'0',
            'has_tu'=>$has_tu,
            'has_wz'=>$has_wz,
          	'has_rw'=>$has_rw,
          	'task_joins'=> $task_joins,
          	'member_uid'=>$member_uid,
          	'seepackage'=>$seepackage,
        ]);
    }



    public function task_join_ajax() {
        $task_id = intval(trim(params('id')));
        $where = ['task_join.task_id' => $task_id];
        $list = \app\home\model\TaskJoin::getTaskPassJoin($where, 15);

        $itemsCallback = function ($item, $key) {
            $username = $item['username'];
            if (strlen($username) >= 11) {
                $item['username'] = substr($username, 0, 3) . "*****" . substr($username, -3);
            }
            return $item;
        };

        $list->each($itemsCallback);

        to_json(0, '', $list);
    }

    //抢单任务
    public function accept(){
        $member = $this->checkLogin();
        $id = input('id');
        if(!check_id($id)){
            message('任务ID错误','','error');
        }
        $has_get_task = db('task_join')->where('uid',$this->member['uid'])->where('task_id',$id)->find();
        $item = \app\home\model\Task::getInfoById($id);
        if(empty($item)){
            message('任务不存在','','error');
        }
        if ($item['start_time'] > TIMESTAMP || $item['origin_end_time'] < TIMESTAMP) {
            message('任务不存在','','error');
        }
        if ($item['is_display'] != 1) {
            message('任务未审核，不可接单','','error');
        }

        if(!empty($this->member['uid']) && $item['uid'] == $this->member['uid']){
            message('无法抢单自己发布的任务','','error');
        }
        
        if(!empty($item['out_stock_flag'])){
        	  message('任务已下架','','error');
        }
        if($item['is_stop']==1){
        	$has_get_task = db('task_join')->where('uid',$this->member['uid'])->where('task_id',$id)->where('delflag',2)->find();
        	if(!$has_get_task){
        		message('任务已暂停','','error');
        	}
        	  
        }
        //查看是否恶意接单被雇主投诉过
        $has_tousu = db('task_join')->where('uid',$member['uid'])->where('task_id',$id)->where('has_tousu',1)->find();
        if($has_tousu){
        	message('由于你恶意投诉雇主，不可再接该单','','error');
        }

         $membes_check = Db::name("member")->where("uid = {$this->member->uid}")->find();
          $taskcheck = Db::name("task")->where("id = {$id}")->find();
        $cageor = Db::name("task_category")->where("id = {$taskcheck['category_id']}")->find();
        if($cageor['only_level'] > $membes_check['level']){
            message("您会员级别不足以接该类别任务",'','error');
        }
	   $my_task_num = db('task_join')->where('uid',$member['uid'])->where('status',1)->where('delflag',1)->count();
        if ($my_task_num>4) {
            message('请先完成已接任务，最多接5个任务','','error');
        }
      
       //修改
        if ($item['join_num'] >= $item['ticket_num']) {
            message('任务抢单人数已满，无法抢单','','error');
        }
      	$my_task_num = db('task_join')->where('uid',$this->member['uid'])->where('task_id',$id)->count();
      	if($my_task_num>=3){
        	message('一个任务最多做三次','','error');
        }
        //检查此人是否重新领取任务，重新领取就直接修改，不能删除再领了，浪费发布人的钱
        $member_task_join_info = \app\home\model\TaskJoin::getInfoByTaskIdAndUid($id, $this->member['uid']);
        if ($member_task_join_info) {
          	if ($member_task_join_info['status'] == 4 || $member_task_join_info['delflag'] == 2) {
          		$update_data['thumbs'] = '';
          		$update_data['check_text_content'] = '';
          		$update_data['communication'] = '';
          		$update_data['status'] = 1;
          		$update_data['delflag'] = 1;
          		$update_data['check_text_content2'] = '';
          		$update_data['times'] = $member_task_join_info['times']+1;
          		$my_update = db('task_join')->where('uid',$this->member['uid'])->where('task_id',$id)->update($update_data);
          		if($my_update){
          			Db::commit();
          			message('重新领取成功','reload','success');
          			
          		}else{
          			Db::rollback();
          			message('抢单失败:-1','','error');
          		}
          		
        	}
        }else{
        	$params = array(
            'task_id' => $id,
            'uid' => $member['uid'],
            'status' => 1,
            'update_time' => TIMESTAMP
        	);
	        $insert_join_id = \app\home\model\TaskJoin::addInfo($params);
	        if(!$insert_join_id){
	            Db::rollback();
	            message('抢单失败:-1','','error');
	        }
	        
	        $status = \app\home\model\Task::incJoinNum($id);
	        if(!$status){
	            Db::rollback();
	            message('抢单失败:-2','','error');
	        }
	
	        //修改
	        if ($item['join_num'] + 1 >= $item['ticket_num']) {
	            $status = \app\home\model\Task::updateInfoById($id, ['is_stop'=>1]);
	            if(!$status){
	                Db::rollback();
	                message('抢单失败:-3','','error');
	            }
	        }
	
	        Db::commit();
	        message('抢单成功','reload','success');
	        }
        
    }








    //添加任务
    public function add(){
        $member = $this->checkLogin();
        $setting = ['push_check' => 0];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['period'])){
                $setting['period'] = explode('#',$setting['period']);
            }
          if($member['level']==1){
            if(!empty($setting['fee'])){
                $setting['fee'] = round(floatval($setting['fee']*0.01),2);
            }
          }else{
            if(!empty($setting['fee_member'])){
                $setting['fee'] = round(floatval($setting['fee_member']*0.01),2);
            }
          }
            if(!empty($setting['push_check'])){
                $setting['push_check'] = intval($setting['push_check']);
            }
        }  

        //如果是ajax请求，处理发布
        if(request()->isAjax()){

            if(!check_array($setting)){
                message('平台未进行相关设置','','error');
            }
            $params = array_trim(request()->post());
            $membes_check = Db::name("member")->where("uid = {$this->member->uid}")->find();
            $cageor = Db::name("task_category")->where("id = {$params['category_id']}")->find();
            if($cageor['only_level'] > $membes_check['level']){
                message("您会员级别不足以在该类别发布任务",'','error');
            }
            if($params['unit_price']<0.2){
            	message("最低佣金不能少于0.2",'','error');
            }
            if($params['unit_price']<$cageor['min_give_credit2']){
            	message("最低佣金为".$cageor['min_give_credit2'],'','error');
            }
            
            
           // var_dump($membes_check);die;
            $params['fee'] = !empty($setting['fee'])?$setting['fee']:0;

            //处理是否的值
            param_is_or_no(['is_screenshot','is_ip_restriction','is_limit_speed'],$params);
            //处理两位小数的值
            params_round(['unit_price','give_credit2'],$params,2);
            //处理是整数的
            params_floor(['check_period','rate','interval_hour','limit_ticket_num'],$params);

            $params['give_credit1'] = intval($params['give_credit1']);
            $params['ticket_num'] = intval($params['ticket_num']);
            $params['give_credit2'] = $params['unit_price'] * $params['ticket_num'];
            $params['amount'] = $params['give_credit2'] * (1 + $params['fee']);

            $result = $this->validate($params,'Task');
            if($result !== true){
                message($result,'','error');
            }
            //判断余额或者积分是足够
            if($params['amount'] > $member['credit2']){
                message('账户余额不足','','error');
            }
            if($params['give_credit1'] > $member['credit1']){
                message('积分不足','','error');
            }

            $task_operate_steps_contents = json_decode(request()->post('step'),true);
            unset($params['process_sm']);
            unset($params['processFile']);
            unset($params['step']);

			//var_dump($task_operate_steps_contents);exit;
            if (empty($task_operate_steps_contents)) {
                message('您未写操作说明!','','error');
            }
            $index1 = 0;
            $index2 = 0;
            $index3 = 0;
            $index4 = 0;
            foreach ($task_operate_steps_contents as $key => $value) {
                if (empty($value[1]) || empty($value[2]) ) {
                    message('您未写操作说明!','','error');
                }
                if($value[0]==1){
                    $index1++;
                }
                if($value[0]==2){
                    $index2++;
                }
                if($value[0]==3){
                    $index3++;
                }
                if($value[0]==4){
                    $index4++;
                }
            }
            if($index2<1){
                message('收集截图不能少于1个!','','error');
            }
            if($index4<1){
                message('图文说明不能少于1个!','','error');
            }

            if($index1>2){
                message('收集信息不能超过2个!','','error');
            }
            if($index2>5){
                message('收集截图不能超过5个!','','error');
            }
            if($index3>1){
                message('网址跳转不能超过1个!','','error');
            }
            if($index4>5){
                message('图文说明不能超过5个!','','error');
            }

            $thumbs_arrs = [];
            foreach ($task_operate_steps_contents as $key => $v) {
                if(in_array($v[0], [2,4])){
                    $thumbs_arrs[] = $key;
                }
            }
            // 获取表单上传文件
            $thumbs = [];
            $files = request()->file('thumbs');
            if(check_array($files)){
                foreach($files as $k=>$file){
                    //七牛
                    $qninfo = $this->qiniuupload($file);
                    if(!$qninfo){
                        message('图片错误','','error');
                    }
                    //七牛
                    //记录文件信息
                    array_push($thumbs,'http://'.$qninfo);
                    $task_operate_steps_contents[$thumbs_arrs[$k]][2] = 'http://'.$qninfo;
                }
            }
            $params['thumbs'] = check_array($thumbs)?serialize($thumbs):'';
      
            //$params['start_time'] = strtotime($params['start_time']);
            $params['start_time']=strtotime("now");//开始时间
            $params['end_time'] = strtotime($params['end_time']);
            $params['check_period_time'] = intval($params['check_period']) * 3600 + TIMESTAMP;
            $params['uid'] = $this->member['uid'];
            $params['update_time'] = TIMESTAMP;

            // 上传操作说明配图
            $task_operate_steps_images = [];
            $task_operate_steps_files = request()->file('processFile');
            if(check_array($task_operate_steps_files)){
                foreach($task_operate_steps_files as $file){
                    //七牛
                    $qninfo = $this->qiniuupload($file);
                    if(!$qninfo){
                        message('图片错误','','error');
                    }
                    //七牛
                    //记录文件信息
                    array_push($task_operate_steps_images, 'http://'.$qninfo);
                }
            }

            //读取后台任务是否需要审核配置
            $params['is_display'] = $setting['push_check'] ? 0 : 1;
          
          //增加平台赠送积分
          $params['give_credit1'] = $setting['jifenbeishu']*$params['unit_price'];
         
            
            Db::startTrans();
            $insert_task_id = \app\home\model\Task::addInfo($params);
            if(!$insert_task_id){
         
                Db::rollback();
                message('发布失败:-1','','error');
            }

            foreach ($task_operate_steps_contents as $key => $value) {
                $task_operate_steps_params = array(
                    'task_id' => $insert_task_id,
                    'uid' => $this->member['uid'],
                    'content' => $value[1],
                    'content2' => in_array($value[0], [1,3])?$value[2]:'',
                    'image' => in_array($value[0], [2,4])?$value[2]:'',
                    'sort' => $key,
                    'type'=> $value[0],
                );

                $insert_task_operate_step_id = \app\home\model\TaskOperateSteps::addInfo($task_operate_steps_params);
                if(!$insert_task_operate_step_id){
                    Db::rollback();
                    message('发布失败:-2','','error');
                }
            }

            if($params['give_credit1']>0 || $params['amount']>0){
                $status1 = Member::updateCreditById($member['uid'], 0, -$params['amount']);
                if(!$status1){
                    Db::rollback();
                    message('发布失败:-3','','error');
                }
                //分别记录积分和余额记录
                
                if($params['amount']>0){
                    $status3 = CreditRecord::addInfo([
                        'uid' => $member['uid'],
                        'type' => 'credit2',
                        'num' => -$params['amount'],
                        'title' => '发布任务',
                        'remark' => "任务[{$insert_task_id}]-" . $params['title'] . "发布成功，扣除{$params['amount']}余额。",
                        'create_time' => TIMESTAMP
                    ]);
                    if(!$status3){
                        Db::rollback();
                        message('发布失败:-5','','error');
                    }
                }  
            }
            Db::commit();
            message('发布成功','/home/mytask.html','success');
        }
        $categories = TaskCategory::getList();

        return $this->fetch(__FUNCTION__,[  
            'item' => ['category_id' => 0],
            'member' => $member,
            'categories' => $categories,
            'setting' => $setting,
            'provinces' => Area::$provinces,
            'operate_steps' => null
        ]);
    }
    
    
    
    //添加任务
    public function create(){
        $member = $this->checkLogin();
        $setting = ['push_check' => 0];
        $config = Config::getInfo();
        
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['period'])){
                $setting['period'] = explode('#',$setting['period']);
            }
          if($member['level']==1){
            if(!empty($setting['fee'])){
                $setting['fee'] = round(floatval($setting['fee']*0.01),2);
            }
          }else{
            if(!empty($setting['fee_member'])){
                $setting['fee'] = round(floatval($setting['fee_member']*0.01),2);
            }
          }
            if(!empty($setting['push_check'])){
                $setting['push_check'] = intval($setting['push_check']);
            }
        }  

        //如果是ajax请求，处理发布
        if(request()->isAjax()){

            if(!check_array($setting)){
                message('平台未进行相关设置','','error');
            }
            $params = array_trim(request()->post());
            
            $params['give_credit1'] = 0;

       
             $params['top_time']=0;
             $params['top_fee']=0;
             $params['top_end_time']=0;
            $params['check_period_time']=time();
            $params['check_text_content']='';
            $params['remarks']='';
            $params['task_checkout_time']=$params['task_checkout_time']*24;
/*            $params['out_stock_flag']=0;
            $params['out_stock_time	']=0;
            $params['admin_id']='';
            $params['audit_remarks']='';
            $params['is_stop']=0;
            $params['is_dj']=0;
            $params['dj_reason']='';*/
            
            $membes_check = Db::name("member")->where("uid = {$this->member->uid}")->find();
            $cageor = Db::name("task_category")->where("id = {$params['category_id']}")->find();
            
            if($cageor['only_level'] > $membes_check['level']){
                message("您会员级别不足以在该类别发布任务",'','error');
            }
            if($params['unit_price']<0.2){
            	message("最低佣金不能少于0.2",'','error');
            }
            if($params['unit_price']<$cageor['min_give_credit2']){
            	message("最低佣金为".$cageor['min_give_credit2'],'','error');
            }
            
            
           // var_dump($membes_check);die;
            $params['fee'] = !empty($setting['fee'])?$setting['fee']:0;

            //处理是否的值
            param_is_or_no(['is_screenshot','is_ip_restriction','is_limit_speed'],$params);
            //处理两位小数的值
            params_round(['unit_price','give_credit2'],$params,2);
            //处理是整数的
            params_floor(['check_period','rate','interval_hour','limit_ticket_num'],$params);

            //$params['give_credit1'] = intval($params['give_credit1']);
      
            
            $params['give_credit2'] = $params['unit_price'] * $params['ticket_num'];
            $params['amount'] = $params['give_credit2'] * (1 + $params['fee']);
        // dump($params);
            $result = $this->validate($params,'Task');
            if($result !== true){
                message($result,'','error');
            }
            //判断余额或者积分是足够
            if($params['amount'] > $member['credit2']){
                message('账户余额不足','','error');
            }
            if($params['give_credit1'] > $member['credit1']){
                // message('积分不足','','error');
            }

			//任务步骤
            $task_operate_steps_contents = request()->post('step/a');
         // dump($task_operate_steps_contents);die;
     /*       unset($params['process_sm']);
            unset($params['processFile']);
            unset($params['step']);*/

			//var_dump($task_operate_steps_contents);exit;
            if (empty($task_operate_steps_contents)) {
                message('您未写任务步骤!','','error');
            }
            $index1 = 0;  //图文
            $index2 = 0; //网址
     
            foreach ($task_operate_steps_contents['type'] as $key => $value) {
            /*	dump($key);
            	dump($value);die;*/
                if (empty($task_operate_steps_contents['text'][$key]) )  {
                    message('您未写步骤说明!','','error');
                }
                
                 if($value == 4){
                	if(!$task_operate_steps_contents['url'][$key]){
                		message('您未上传步骤截图!','','error');
                	}
                }
                
                if($value==4){
                    $index1++;
                }

            }
            if($index1<1){
                message('图文步骤不能少于1个!','','error');
            }
     
            if($index1>5){
                message('图文步骤不能超过5个!','','error');
            }

      
            //$params['start_time'] = strtotime($params['start_time']);
            $params['start_time']=strtotime("now");//开始时间
            $params['end_time'] = strtotime($params['end_time']);
            $params['check_period_time'] = intval($params['check_period']) * 3600 + TIMESTAMP;
            $params['uid'] = $this->member['uid'];
            $params['update_time'] = TIMESTAMP;


            //读取后台任务是否需要审核配置
            $params['is_display'] = $setting['push_check'] ? 0 : 1;
          
          //增加平台赠送积分
          $params['give_credit1'] =0;
          
          unset($params['contents']);
          unset($params['step']);
          unset($params['info']);
          unset($params['is_guize']);
         
        
          
            Db::startTrans();
            
            $insert_task_id = \app\home\model\Task::addInfo($params);
       
            if(!$insert_task_id){
         
                Db::rollback();
                message('发布失败:-1','','error');
            }

            foreach ($task_operate_steps_contents['type'] as $key => $value) {
            	
                $task_operate_steps_params = array(
                    'task_id' => $insert_task_id,
                    'uid' => $this->member['uid'],
                    'content' => $task_operate_steps_contents['text'][$key],
                    'content2' =>  $value == 3 ?$task_operate_steps_contents['url'][$key]:'',
                    'image' => $value == 4 ? $task_operate_steps_contents['url'][$key]:'',
                    'sort' => $key,
                    'type'=> $task_operate_steps_contents['type'][$key],
                );

/*dump($task_operate_steps_contents);
dump($task_operate_steps_params);
die;*/
                $insert_task_operate_step_id = \app\home\model\TaskOperateSteps::addInfo($task_operate_steps_params);
                if(!$insert_task_operate_step_id){
                    Db::rollback();
                    message('发布失败:-2','','error');
                }
            }

		$count=count($task_operate_steps_contents['type']);
		//收集数据
		 $task_operate_info_contents = request()->post('info/a');
		 
if(!$task_operate_info_contents){
                    message('您未写验证步骤!','','error');
	
}

			$index3=0;
            foreach ($task_operate_info_contents['type'] as $key => $value) {
            /*	dump($key);
            	dump($value);die;*/
                if (empty($task_operate_info_contents['text'][$key]) )  {
                    message('您未写验证说明!','','error');
                }
                
                if($value == 2){
                	if(!$task_operate_info_contents['url'][$key]){
                		message('您未上传验证截图!','','error');
                	}
                }
        
                   $index3++;
    
            }
            if($index3<1){
                message('验证步骤不能少于1个!','','error');
            }
     


            foreach ($task_operate_info_contents['type'] as $key => $value) {
            	
                $task_operate_steps_params = array(
                    'task_id' => $insert_task_id,
                    'uid' => $this->member['uid'],
                    'content' => $task_operate_info_contents['text'][$key],
                    'content2' =>  $value == 1 ?$task_operate_info_contents['url'][$key]:'',
                    'image' => $value == 2 ? $task_operate_info_contents['url'][$key]:'',
                    'sort' => $key+$count,
                    'type'=> $task_operate_info_contents['type'][$key],
                );

/*dump($task_operate_steps_contents);
dump($task_operate_steps_params);
die;*/
                $insert_task_operate_step_id = \app\home\model\TaskOperateSteps::addInfo($task_operate_steps_params);
                if(!$insert_task_operate_step_id){
                    Db::rollback();
                    message('发布失败:-2','','error');
                }
            }




            if($params['give_credit1']>0 || $params['amount']>0){
                $status1 = Member::updateCreditById($member['uid'], 0, -$params['amount']);
                if(!$status1){
                    Db::rollback();
                    message('发布失败:-3','','error');
                }
                //分别记录积分和余额记录
                
                if($params['amount']>0){
                    $status3 = CreditRecord::addInfo([
                        'uid' => $member['uid'],
                        'type' => 'credit2',
                        'num' => -$params['amount'],
                        'title' => '发布任务',
                        'remark' => "任务[{$insert_task_id}]-" . $params['title'] . "发布成功，扣除{$params['amount']}余额。",
                        'create_time' => TIMESTAMP
                    ]);
                    if(!$status3){
                        Db::rollback();
                        message('发布失败:-5','','error');
                    }
                }  
            }
            Db::commit();
            message('发布成功','/home/mytask.html','success');
        }
        $categories = TaskCategory::getList();
        $arr_Price=[];
        $arr_Votes=[];
        $displayValues = [];
        $values = [];
        foreach ($categories as $key => $v){
            array_push($arr_Price,$v['min_give_credit2']);
            array_push($arr_Votes,$v['min_piaoshu']);
            array_push($displayValues,$v['title']);
            array_push($values,$v['id']);
        }
        
       // $this->assign("aaa",$result);

        //echo json_encode($result);
        return $this->fetch(__FUNCTION__,[  
            'item' => ['category_id' => 0],
            'member' => $member,
            'arr_Price' => json_encode($arr_Price),
            'arr_Votes' => json_encode($arr_Votes),
            'displayValues' => json_encode($displayValues),
            'values' => json_encode($values),
            'setting' => $setting,
            'provinces' => Area::$provinces,
            'operate_steps' => null
        ]);
    }









 
    
    
    
    //显示最低悬赏数量
    public function category_change(){
        $result = db('task_category')->where('id',input('id'))->find();
        echo json_encode($result,256);
    }

    //编辑任务
    public function edit($id = 0) {
        $member = $this->checkLogin();
        $setting = [];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['period'])){
                $setting['period'] = explode('#',$setting['period']);
            }
            if(!empty($setting['fee'])){
                $setting['fee'] = round(floatval($setting['fee']*0.01),2);
            }
        }

        if(!check_id($id)){
            message('任务ID错误','','error');
        }
        $item = \app\home\model\Task::getInfoById($id);
        if(empty($item)){
            message('任务不存在','','error');
        }
        if(empty($this->member['uid']) || $item['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }
        if($item['join_num'] > 0){
            message('任务状态不允许编辑','','error');
        }

        $operate_steps = \app\home\model\Task::getOperateStepsById($id);
        if ($operate_steps) {
            foreach ($operate_steps as $key => $value) {
                $operate_steps[$key]['content'] = str_replace(array("\r", "\n"), array("", "\\n"), $value['content']);
            }
        }

        $categories = TaskCategory::getList();
        
        var_dump($operate_steps);die;
        return $this->fetch('add', [
            'member' => $member,
            'categories' => $categories,
            'setting' => $setting,
            'provinces' => Area::$provinces,
            'item' => $item,
            'operate_steps' => $operate_steps
        ]);
    }

    //编辑任务
    public function save() {
        $member = $this->checkLogin();
        $setting = [];
        $config = Config::getInfo();
        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['period'])){
                $setting['period'] = explode('#',$setting['period']);
            }
            if(!empty($setting['fee'])){
                $setting['fee'] = round(floatval($setting['fee']*0.01),2);
            }
        }

        $id = floor(trim(params('id')));
        if(!check_id($id)){
            message('任务ID错误','','error');
        }
        $item = \app\home\model\Task::getInfoById($id);
        if(empty($item)){
            message('任务不存在','','error');
        }
        if(empty($this->member['uid']) || $item['uid'] != $this->member['uid']){
            message('任务不存在','','error');
        }
        if($item['join_num'] > 0){
            message('任务状态不允许编辑','','error');
        }

        $params = array_trim(request()->post());
        if($params['category_id'] !=$item['category_id']){
        	message('任务类型不允许更改','','error');
        }
        $result = $this->validate($params,'Task');
        if($result !== true){
            message($result,'','error');
        }
        $cageor = Db::name("task_category")->where("id = {$item['category_id']}")->find();
		if($params['unit_price']<$cageor['min_give_credit2']){
            	message("最低佣金为".$cageor['min_give_credit2'],'','error');
            }

        $params['fee'] = !empty($setting['fee'])?$setting['fee']:0;

        //处理是否的值
        param_is_or_no(['is_screenshot','is_ip_restriction','is_limit_speed'],$params);
        //处理两位小数的值
        params_round(['unit_price','give_credit2'],$params,2);
        //处理是整数的
        params_floor(['check_period','rate','interval_hour','limit_ticket_num'],$params);

        $params['give_credit1'] = intval($params['give_credit1']);
        $params['ticket_num'] = intval($params['ticket_num']);
        $params['give_credit2'] = floatval($params['unit_price'] * $params['ticket_num']);
        $params['amount'] = floatval($params['give_credit2'] * (1 + $params['fee']));

        //判断余额或者积分是足够
        if($params['amount'] > $member['credit2']){
            message('账户余额不足','','error');
        }
 
        $task_operate_steps_contents = json_decode(request()->post('step'),true);
        // $task_operate_steps_contents = $params['process_sm'];
        unset($params['process_sm']);
        unset($params['processFile']);
        unset($params['step']);

        if (empty($task_operate_steps_contents)) {
            message('您未写操作说明!','','error');
        }
        foreach ($task_operate_steps_contents as $key => $value) {
            if (empty($value)) {
                message('您未写操作说明!','','error');
            }
        }

        $thumbsi = isset($_POST["thumbsi"]) && is_array($_POST["thumbsi"]) ? $_POST["thumbsi"] : [];
        $thumbs = [];

        if (is_array($item['thumbs'])) {
            foreach ($item['thumbs'] as $key => $value) {
                if (in_array($key, $thumbsi)) {
                    $thumbs[] = $value;
                }
            }
        }
        

        $thumbs_arrs = [];
        foreach ($task_operate_steps_contents as $key => $v) {
            if(in_array($v[0], [2,4]) && strrpos($v[2], 'blob:') !== false){
                $thumbs_arrs[] = $key;
            }
        }
        // 获取表单上传文件
        $files = request()->file('thumbs');
        if(check_array($files)){
            foreach($files as $k=>$file){
               //七牛
                    $qninfo = $this->qiniuupload($file);
                    message($qninfo,'','error');
                    if(!$qninfo){
                        message('图片错误','','error');
                    }
                    //七牛

                //记录文件信息
                array_push($thumbs,'http://'.$qninfo);
                $task_operate_steps_contents[$thumbs_arrs[$k]][2] = 'http://'.$qninfo;
                
            }
        }
        $params['thumbs'] = check_array($thumbs)?serialize($thumbs):'';
        $params['start_time'] = strtotime($params['start_time']);
        $params['end_time'] = strtotime($params['end_time']);
        $params['check_period_time'] = intval($params['check_period']) * 3600 + TIMESTAMP;
        $params['is_display'] = 0;
        $params['admin_id'] = 0;
        $params['update_time'] = TIMESTAMP;

     //读取旧的操作说明步骤
        $operate_steps = \app\home\model\Task::getOperateStepsById($id);
        $operate_step_ids = isset($_POST["operate_step_id"]) && is_array($_POST["operate_step_id"]) ? $_POST["operate_step_id"] : [];

        $operate_step_del_ids = [];
        $operate_steps_last_sort = 0;

        //先把旧的操作步骤已经删除的unset
        foreach ($operate_steps as $key => $value) {
            if (!in_array($value['id'], $operate_step_ids)) {
                $operate_step_del_ids[] = $value['id'];
                unset($operate_steps[$key]);
            }

            $operate_steps_last_sort = $value['sort'];
        }

       

        Db::startTrans();
       db('task_operate_steps')->where('task_id',$id)->delete();


    	
        unset($params['thumbsi']);
        unset($params['operate_step_id']);
        
        $insert_task_id = $id;
        $status0 = \app\home\model\Task::updateInfoById($id, $params);
        if(!$status0){
            Db::rollback();
            message('保存失败:-3','','error');
        }
        foreach ($task_operate_steps_contents as $key => $value) {
            $task_operate_steps_params = array(
                'task_id' => $insert_task_id,
                'uid' => $this->member['uid'],
                'content' => $value[1],
                'content2' => in_array($value[0], [1,3])?$value[2]:'',
                'image' => in_array($value[0], [2,4])?$value[2]:'',
                'sort' => $operate_steps_last_sort + 1,
                    'type'=> $value[0],

            );

            $insert_task_operate_step_id = \app\home\model\TaskOperateSteps::addInfo($task_operate_steps_params);
            if(!$insert_task_operate_step_id){
                Db::rollback();
                message('保存失败:-4','','error');
            }
        }

        if($item['give_credit1'] != $params['give_credit1'] || bccomp($item['amount'], $params['amount'], 2) != 0){
            if($item['give_credit1']>0 || $item['amount']>0){
                $status1 = Member::updateCreditById($member['uid'], $item['give_credit1'], $item['amount']);
                if(!$status1){
                    Db::rollback();
                    message('保存失败:-5','','error');
                }
                //分别记录积分和余额记录
               
                if($item['amount']>0){
                    $status3 = CreditRecord::addInfo([
                        'uid' => $member['uid'],
                        'type' => 'credit2',
                        'num' => $item['amount'],
                        'title' => '编辑任务',
                        'remark' => "任务[{$insert_task_id}]-" . $params['title'] . "保存成功，退回原{$item['amount']}余额。",
                        'create_time' => TIMESTAMP
                    ]);
                    if(!$status3){
                        Db::rollback();
                        message('保存失败:-7','','error');
                    }
                }
            }

            if($params['give_credit1']>0 || $params['amount']>0){
                $status1 = Member::updateCreditById($member['uid'],0, -$params['amount']);
                if(!$status1){
                    Db::rollback();
                    message('保存失败:-8','','error');
                }
                //分别记录积分和余额记录
             
                if($params['amount']>0){
                    $status3 = CreditRecord::addInfo([
                        'uid' => $member['uid'],
                        'type' => 'credit2',
                        'num' => -$params['amount'],
                        'title' => '编辑任务',
                        'remark' => "任务[{$insert_task_id}]-" . $params['title'] . "保存成功，扣除新{$params['amount']}余额。",
                        'create_time' => TIMESTAMP
                    ]);
                    if(!$status3){
                        Db::rollback();
                        message('保存失败:-10','','error');
                    }
                }
            }
        }

        Db::commit();

        message('保存成功','/home/mytask.html','success');
    }
   

public function daily_task(){
	$member=$this->checkLogin();
	$today=strtotime(date('Y-m-d'));
	//今天完成的任务
	$count=db('task_join')->where(['uid'=>$member['uid'],'status'=>3,'audit_time'=>['gt',$today]])->count();
	
	$task_3=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_3'])->count();
	$task_6=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_6'])->count();
	$task_11=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_11'])->count();
	$task_19=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_19'])->count();
	$task_31=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_31'])->count();
	
$surplus=86400-(time()-strtotime(date('Y-m-d')));
//	$surplus=86400-(time()%86400)-8*3600;
	  return $this->fetch('', [
	  	'surplus'=>$surplus,
	  	'count'=>$count,
	  	'task_3'=>$task_3,
	  	'task_6'=>$task_6,
	  	'task_11'=>$task_11,
	  	'task_19'=>$task_19,
	  	'task_31'=>$task_31,
        ]);
   
}




  public function get_reward(){
  	$member = $this->checkLogin();
  	$type=input('type');
  	$today=strtotime(date('Y-m-d'));
  	$count=db('task_join')->where(['uid'=>$member['uid'],'status'=>3,'audit_time'=>['gt',$today]])->count();
  	
	$task_3=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_3'])->count();
	$task_6=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_6'])->count();
	$task_11=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_11'])->count();
	$task_19=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_19'])->count();
	$task_31=db('daily_task')->where(['uid'=>$member['uid'],'add_time'=>['gt',$today],'title'=>'task_31'])->count();
  	
  	  	if($type == 'task_3'){
  	  		if($task_3){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		if($count<3){
  	  			 message('任务未完成','reload','error');
  	  		}
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+0.2;
	  		
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 0.2,
			                    'title' => '完成3个任务奖励',
			                    'remark' => "完成3个任务奖励，奖励0.2元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //更新数据
			                $task_data=[
			                	'uid'=>$member['uid'],
			                	'title'=>'task_3',
			                	'num'=>0.2,
			                	'add_time'=>time(),
			                	];
			                db('daily_task')->insert($task_data);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  	}
	  	


  	  	if($type == 'task_6'){
  	  		if($task_6){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		if($count<6){
  	  			 message('任务未完成','reload','error');
  	  		}
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+0.3;
	  		
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 0.3,
			                    'title' => '再完成3个任务奖励',
			                    'remark' => "再完成3个任务奖励，奖励0.3元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //更新数据
			                $task_data=[
			                	'uid'=>$member['uid'],
			                	'title'=>'task_6',
			                	'num'=>0.3,
			                	'add_time'=>time(),
			                	];
			                db('daily_task')->insert($task_data);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  	}


  	  	if($type == 'task_11'){
  	  		if($task_11){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		if($count<11){
  	  			 message('任务未完成','reload','error');
  	  		}
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+0.5;
	  		
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 0.5,
			                    'title' => '再完成5个任务奖励',
			                    'remark' => "再完成5个任务奖励，奖励0.5元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //更新数据
			                $task_data=[
			                	'uid'=>$member['uid'],
			                	'title'=>'task_11',
			                	'num'=>0.5,
			                	'add_time'=>time(),
			                	];
			                db('daily_task')->insert($task_data);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  	}
	  	


  	  	if($type == 'task_19'){
  	  		if($task_19){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		if($count<19){
  	  			 message('任务未完成','reload','error');
  	  		}
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+1;
	  		
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 1,
			                    'title' => '再完成8个任务奖励',
			                    'remark' => "再完成8个任务奖励，奖励1元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //更新数据
			                $task_data=[
			                	'uid'=>$member['uid'],
			                	'title'=>'task_19',
			                	'num'=>1,
			                	'add_time'=>time(),
			                	];
			                db('daily_task')->insert($task_data);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  	}



  	  	if($type == 'task_31'){
  	  		if($task_31){
  	  			 message('您已领取奖励，不能重复领取','reload','error');
  	  		}
  	  		if($count<31){
  	  			 message('任务未完成','reload','error');
  	  		}
	  			//增加用户余额
	  			$data['credit2'] = $member['credit2']+1.5;
	  		
	  			  $res = db('member')->where('uid',$member['uid'])->update($data);
	  			  if($res){
	  			  	
			        	CreditRecord::addInfo([
			                    'uid' => $member['uid'],
			                    'type' => 'credit2',
			                    'num' => 1.5,
			                    'title' => '再完成12个任务奖励',
			                    'remark' => "再完成12个任务奖励，奖励1.5元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
			                
			                //更新数据
			                $task_data=[
			                	'uid'=>$member['uid'],
			                	'title'=>'task_31',
			                	'num'=>1.5,
			                	'add_time'=>time(),
			                	];
			                db('daily_task')->insert($task_data);
			                
			                message('领取成功','/home/account.html','success');
	  			  }
	  	}

  }



  public function redpackage(){
  	//$data=random_red($total, $num, $max, $min);
  		$task_id=params('task_id');
  		$redpackage=db('redpackage')->alias('a')->where(['task_id'=>$task_id])->join('member b','a.uid = b.uid')->find();
  		$redpackage_record=db('redpackage_record')->alias('a')->where(['task_id'=>$task_id,'a.uid'=>['neq',0]])->join('member b','a.uid = b.uid')->select();
  	
        return $this->fetch(__FUNCTION__,[
			'redpackage'=>$redpackage,
			'redpackage_record'=>$redpackage_record,
			
        ]);
  }



public  function send_seepackage(){
 		$member = $this->checkLogin();
		$task_id=input('task_id');
		if(!$task_id){
			message('缺少参数','','error');
		}
		//发红包
		$uid=$member['uid'];
		
		
			$is_money=\db('seepackage_record')->where(['task_id'=>$task_id,'uid'=>$uid])->find();
			if($is_money){
				message('已获得浏览红包:-4','','error');
			}
		
		
		$seepackage=db('seepackage')->where(['task_id'=>$task_id,'is_over'=>0,'is_back'=>0])->find();
		
		if($seepackage){
				$has_send_money=\db('seepackage_record')->where(['task_id'=>$task_id,'seepackage_id'=>$seepackage['seepackage_id']])->sum('money');
				$has_send_number=\db('seepackage_record')->where(['task_id'=>$task_id,'seepackage_id'=>$seepackage['seepackage_id']])->count();
	
				if($has_send_number <$seepackage['number']){
					
					//要发的红包
				
							//是否最后一个用户
							if( ($has_send_number+1) == $seepackage['number'] ){
								$seepackage['is_over']=1;
								\db('seepackage')->update($seepackage);
							}
							
							$get_money=$seepackage['money'];
							
						     $credit2 = $member['credit2']+$get_money;
					    
					          $res1 = Member::updateCreditById($uid, 0, $get_money);
					          
					            if(!$res1){
						            message('操作失败:-3','','error');
						        }
		
		
					        $creditdata = array(
					            'uid'=>$uid,
					            'type'=>'credit2',
					            'num'=>'+'.$get_money,
					            'title'=>'浏览任务获得红包',
					            'remark'=>'浏览任务'.$task_id.'获得红包'.$get_money,
					            'create_time'=>time(),
					            'balance'=>$credit2,    //追加后的余额
					        );
					        $res3 = \db('credit_record')->data($creditdata)->insert();
					        if(!$res3){
					            message('获取失败:-5','','error');
					        }
					        
					        
					       $send_info=[
					       		'uid'=>$uid,
					       		'task_id'=>$task_id,
					       		'money'=>$get_money,
					       		'seepackage_id'=>$seepackage['seepackage_id'],
					       		'add_time'=>time()
					       	];
					        
					       $res4 = \db('seepackage_record')->insert($send_info);
					        if(!$res4){
					            message('发红包失败失败:-6','','error');
					        }
					        
					        
					        message('获得浏览红包成功','','success');
	
				}
				        
				}
				
				message('获取失败:-4','','error');
		}  




}
